package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.pojo.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.RedisKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by ZhaoJun on 2021/11/27 14:59
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user) {
        log.info("controller--sendMsg--phone:{}", user.getPhone());
        String phone = user.getPhone();
        String checkCode = userService.sendMsg(phone);
//        request.getSession().setAttribute(phone, checkCode);
        //将验证码缓存到redis中并设置5分钟有效期
        redisTemplate.opsForValue().set(RedisKeys.RG_CODE+phone,checkCode,5, TimeUnit.MINUTES);
        return R.success("验证码发送成功");

    }

    @PostMapping("/login")
    public R login(@RequestBody Map map) {
        log.info("controller--login--map:{}", map.toString());

        String phone = (String) map.get("phone");
        String code = (String) map.get("code");

        //存在，判断验证码是否正确
        HttpSession session = request.getSession();
        String redisCheckCode = (String)redisTemplate.opsForValue().get(RedisKeys.RG_CODE+phone);
//        String redisCheckCode = (String) session.getAttribute(phone);


        if (redisCheckCode == null) {
            return R.error("验证码获取失败");
        }
        if (!redisCheckCode.equals(code)) {
            return R.error("验证码不匹配");
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        //号码是否存在
        User one = userService.getOne(lqw);
        //不存在，注册一个并登录
        if (one == null) {
            one = new User();
            one.setPhone(phone);
            one.setStatus(1);
            userService.save(one);
        }

        session.setAttribute("userId", one.getId());
//        session.removeAttribute(phone);
        redisTemplate.delete(RedisKeys.RG_CODE+phone);

        return R.success(one);


    }

    @PostMapping("/loginout")
    public R loginout() {
        request.getSession().removeAttribute("userId");
        return R.success("");
    }


}
